package com.inspur.security.cbb3.kms.keymanager.containers.controller;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inspur.security.cbb3.kms.annotation.SysLog;
import com.inspur.security.cbb3.kms.enums.BusinessType;
import com.inspur.security.cbb3.kms.enums.SystemCode;
import com.inspur.security.cbb3.kms.keymanager.containers.po.ContainersBean;
import com.inspur.security.cbb3.kms.keymanager.containers.service.ContainersService;
import com.inspur.security.cbb3.kms.keymanager.containers.vo.SecretRefVO;
import com.inspur.security.cbb3.kms.keymanager.containersecret.po.ContainerSecretBean;
import com.inspur.security.cbb3.kms.keymanager.containersecret.repository.ContainerSecretRepository;
import com.inspur.security.cbb3.kms.utils.PageRequestDate;
import com.inspur.security.cbb3.kms.utils.ResultUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import javassist.NotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 密钥容器控制类
 *
 * @author lijunchang
 */
@RestController
@RequestMapping("/v1/containers")
@ApiModel(value = "密钥容器业务", description = "密钥容器业务")
@Slf4j
public class ContainersController {

    @Autowired
    private ContainersService containersService;
    @Autowired
    private ContainerSecretRepository containerSecretRepository;


    @GetMapping
    @ApiOperation(value = "密钥容器列表查询", notes = "密钥容器列表查询", httpMethod = "GET")
    public ResponseEntity searchContainers(@ApiParam(value = "传入分页条件") PageRequestDate pageRequestDate,
                                           @ApiParam(value = "传入查询条件") ContainersBean searchParams) {
        Page page = containersService.searchContainers(pageRequestDate, searchParams);
        Map<String, Object> returnMap = new HashMap<>(2);
        returnMap.put("total", page.getTotalElements());
        if (page.getTotalElements() < 1) {
            returnMap.put("secrets", null);
            return ResultUtil.objReturn(returnMap, HttpStatus.OK);
        }
        List<ContainersBean> list = page.getContent();
        List<String> uuids = list.stream().map(ContainersBean::getUuid).collect(Collectors.toList());
        List<ContainerSecretBean> containerSecretBeans = containerSecretRepository.findByContainerIdIn(uuids);
        list.forEach(bean -> {
            Optional<ContainerSecretBean> csb = containerSecretBeans.stream().filter(cs ->
                    cs.getContainerId().equalsIgnoreCase(bean.getUuid())
            ).findFirst();
            if (csb.isPresent()) {
                ContainerSecretBean cs = csb.get();
                bean.getSecretRefS().add(new SecretRefVO(cs.getName(), cs.getNote(), "/v1/secrets/" + cs.getSecretId(), cs.getSecretId()));
            }
        });
        returnMap.put("containers", list);
        return ResultUtil.objReturn(returnMap, HttpStatus.OK);
    }

    @GetMapping("/{uuid}")
    @ApiOperation(value = "密钥容器单个信息查询", notes = "密钥容器单个信息查询,请将{uuid}替换成密钥容器主键", httpMethod = "GET")
    public ResponseEntity searchContainers(@PathVariable("uuid") String uuid) throws MissingServletRequestParameterException, NotFoundException {
        ContainersBean bean = containersService.searchContainers(uuid);
        List<ContainerSecretBean> containerSecretBeans = containerSecretRepository.findByContainerId(bean.getUuid());
        containerSecretBeans.forEach(cs ->
                bean.getSecretRefS().add(new SecretRefVO(cs.getName(), cs.getNote(), "/v1/secrets/" + cs.getSecretId(), cs.getSecretId()))
        );
        return ResultUtil.objReturn(bean, HttpStatus.OK);
    }

    @PostMapping
    @ApiOperation(value = "新增密钥容器", notes = "新增密钥容器", httpMethod = "POST")
    @SysLog(title = "密钥容器新增", businessType = BusinessType.INSERT, isSaveRequestData = true)
    public ResponseEntity addContainers(@ApiParam(value = "传入新增密钥对象", required = true) @Valid ContainersBean containersBean) throws NotFoundException, MissingServletRequestParameterException {
        ContainersBean bean = containersService.addContainers(containersBean);
        Map<String, String> returnMap = new HashMap<>(1);
        returnMap.put("containerRef", "/v1/containers/" + bean.getUuid());
        return ResultUtil.objReturn(returnMap, HttpStatus.CREATED);
    }

    @DeleteMapping("/{uuid}")
    @ApiOperation(value = "删除密钥容器", notes = "可以删除一条密钥容器信息", httpMethod = "DELETE")
    @SysLog(title = "删除密钥容器", businessType = BusinessType.DELETE)
    public ResponseEntity deleteContainer(@PathVariable("uuid") String uuid) throws MissingServletRequestParameterException, NotFoundException {
        containersService.deleteContainer(uuid);
        return ResultUtil.noDataReturn(SystemCode.SUCCESS, HttpStatus.NO_CONTENT);
    }

    @PostMapping("/{uuid}/{secretUuid}")
    @ApiOperation(value = "向容器中添加密钥", notes = "向容器中添加密钥", httpMethod = "POST")
    @SysLog(title = "向容器中添加密钥", businessType = BusinessType.UPDATE)
    public ResponseEntity addSecretsToContainer(@PathVariable("uuid") String uuid, @PathVariable("secretUuid") String secretUuid) throws NotFoundException, MissingServletRequestParameterException {
        containersService.addSecretsToContainer(uuid, secretUuid);
        Map<String, String> returnMap = new HashMap<>(1);
        returnMap.put("containerRef", "/v1/containers/" + uuid);
        return ResultUtil.objReturn(returnMap, HttpStatus.CREATED);
    }

    @DeleteMapping("/{uuid}/{secretUuid}")
    @ApiOperation(value = "删除密钥容器中的密钥", notes = "可以删除密钥容器中的一条密钥信息", httpMethod = "DELETE")
    @SysLog(title = "删除密钥容器中的密钥", businessType = BusinessType.DELETE)
    public ResponseEntity deleteSecretsFromContainer(@PathVariable("uuid") String uuid, @PathVariable("secretUuid") String secretUuid) throws NotFoundException, MissingServletRequestParameterException {
        containersService.deleteSecretsFromContainer(uuid, secretUuid);
        Map<String, String> returnMap = new HashMap<>(1);
        returnMap.put("containerRef", "/v1/containers/" + uuid);
        return ResultUtil.objReturn(returnMap, HttpStatus.CREATED);
    }


}
